<template>
  <div class="mod-config">
    <!-- 操作栏 -->
    <el-form>
      <el-form-item>
        <el-button size="mini" v-if="isAuth('goods:goods:export')" type="primary" @click="exportData()()">导出
        </el-button>
        <!-- <el-button size="mini" v-if="isAuth('goods:goods:delete')" type="danger" @click="deleteHandle()"
          :disabled="dataListSelections.length <= 0">删除</el-button> -->
      </el-form-item>
    </el-form>
    <el-divider></el-divider>
    <el-form :inline="true" :model="dataForm" ref="dataFormRef" @keyup.enter.native="getDataList()">
      <el-form-item>
        单位：
        <el-select size="mini" v-model="dataForm.unit" clearable placeholder="请选择" @change="getDataList()" @clear="getDataList()">
          <el-option v-for="item in units" :key="item.value" :label="item.label" :value="item.label">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        选择过滤：
        <el-select size="mini" v-model="dataForm.selectField" clearable placeholder="请选择" @change="getDataList()" @clear="getDataList()">
          <el-option v-for="item in selectFields" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select size="mini" v-model="dataForm.selectValue" clearable placeholder="请选择" @change="getDataList()" @clear="getDataList()">
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="0"></el-option>
        </el-select>
      </el-form-item>
      <!-- profit = localRetailPrice - tradePrice,
       profitRate = (localRetailPrice - tradePrice)/localRetailPrice * 100 -->
      <el-form-item>
        库存/价格/毛利过滤：
        <el-select size="mini" v-model="dataForm.priceField" clearable placeholder="请选择" @change="getDataList()" @clear="getDataList()">
          <el-option v-for="item in priceFields" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select size="mini" v-model="dataForm.priceFormula" clearable placeholder="请选择" @change="getDataList()" @clear="getDataList()">
          <el-option v-for="item in priceFormulas" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input size="mini" v-model="dataForm.priceValue" clearable type="number" placeholder="库存/价格/毛利" @blur="getDataList()" @clear="getDataList()"></el-input>
      </el-form-item>
      <el-form-item>
        查询过滤：
        <el-select size="mini" v-model="dataForm.queryField" clearable placeholder="请选择" @change="getDataList()" @clear="getDataList()">
          <el-option v-for="item in queryFields" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input size="mini" v-model="dataForm.key" placeholder="参数名" clearable @blur="getDataList()" @clear="getDataList()"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()" size="mini" type="success">查询</el-button>
        <el-button @click="resetForm()" size="mini" type="info" >重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="dataList"
      @cell-dblclick="tableDbEdit"
      @selection-change="selectionChangeHandle"
      border size="mini"
      v-loading="dataListLoading"
      style="width: 100%;"
      :header-cell-style="{ background: '#fcfcfc', color: '#606266', height:'36px'}">
      <el-table-column type="selection" header-align="center" align="center" width="50">
      </el-table-column>
      <el-table-column type="index" width="50" header-align="center" align="center" label="序号">
      </el-table-column>
      <el-table-column prop="goodsCode" header-align="center" align="center" label="产品编号">
      </el-table-column>
      <el-table-column prop="goodsName" width="200" header-align="center" align="center" label="产品名称">
      </el-table-column>
      <el-table-column prop="categoryName" header-align="center" align="center" label="类别名称">
      </el-table-column>
      <el-table-column prop="genericName" width="200" header-align="center" align="center" label="通用名">
      </el-table-column>
      <el-table-column prop="producingArea" header-align="center" align="center" label="产地">
      </el-table-column>
      <el-table-column prop="supplierName" width="220" header-align="center" align="center" label="供应商">
      </el-table-column>
      <el-table-column prop="supplierMobile" width="100"  header-align="center" align="center" label="供应商手机">
      </el-table-column>
      <el-table-column prop="standard" width="120" header-align="center" align="center" label="规格">
      </el-table-column>
      <el-table-column prop="unit" header-align="center" align="center" label="单位">
      </el-table-column>
      <el-table-column prop="mnemonicName" header-align="center" align="center" label="助记名">
      </el-table-column>
      <el-table-column prop="status" header-align="center" align="center" label="状态">
        <template slot-scope="scope">
          <el-switch size="mini" v-model="scope.row.status" @change="saveHandle(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="batchNo" header-align="center" align="center" label="批号">
      </el-table-column>
      <el-table-column prop="purchaseSerialNo" header-align="center" align="center" label="批次号">
      </el-table-column>
      <el-table-column prop="storageNo" header-align="center" align="center" label="入库号">
      </el-table-column>
      <el-table-column prop="acceptNo" width="120" header-align="center" align="center" label="验收号">
      </el-table-column>
      <el-table-column prop="receiveNo" width="120" header-align="center" align="center" label="收货单号">
      </el-table-column>
      <el-table-column prop="orderNo" width="120" header-align="center" align="center" label="订货单号">
      </el-table-column>
      <el-table-column prop="supplierDeliveryNo" width="120" header-align="center" align="center" label="配送单号">
      </el-table-column>
      <el-table-column prop="purchaseinvoiceNo" header-align="center" align="center" label="发票号">
      </el-table-column>
      <el-table-column prop="purchaseinvoiceCode" header-align="center" align="center" label="发票编码">
      </el-table-column>
      <el-table-column prop="stockNum" header-align="center" align="center" label="库存">
      </el-table-column>
      <el-table-column prop="purchaseNum" header-align="center" align="center" label="采购数量">
      </el-table-column>
      <el-table-column prop="returnNum" header-align="center" align="center" label="退货数量">
      </el-table-column>
      <el-table-column prop="splitNum" header-align="center" align="center" label="拆零数量">
      </el-table-column>
      <el-table-column prop="saleNum" header-align="center" align="center" label="销售数量">
      </el-table-column>
      <el-table-column prop="checkInNum" header-align="center" align="center" label="盘盈数量">
      </el-table-column>
      <el-table-column prop="checkOutNum" header-align="center" align="center" label="盘亏数量">
      </el-table-column>
      <el-table-column prop="destroyNum" header-align="center" align="center" label="销毁数量">
      </el-table-column>
      <el-table-column prop="purchasePrice" header-align="center" align="center" label="采购价">
      </el-table-column>
      <el-table-column prop="guidePrice" header-align="center" align="center" label="指导价">
      </el-table-column>
      <el-table-column prop="salePrice" header-align="center" align="center" label="售价">
        <template slot-scope="scope">
           <el-input size="mini" v-model="scope.row.salePrice" v-if="showInput == `salePrice${scope.row.stockId}`"
             @blur='blurInput(scope.row, "salePrice", scope.row.salePrice)' v-focus>
           </el-input>
           <span v-else>{{scope.row.salePrice}}</span>
         </template>
      </el-table-column>
      <el-table-column prop="memberPrice" header-align="center" align="center" label="会员价">
        <template slot-scope="scope">
           <el-input size="mini" v-model="scope.row.memberPrice" v-if="showInput == `memberPrice${scope.row.stockId}`"
             @blur='blurInput(scope.row, "memberPrice", scope.row.memberPrice)' v-focus>
           </el-input>
           <span v-else>{{scope.row.memberPrice}}</span>
         </template>
      </el-table-column>
      <el-table-column prop="barCode" header-align="center" align="center" label="条码">
      </el-table-column>
      <el-table-column prop="isRxDrug" header-align="center" align="center" label="处方药">
      </el-table-column>
      <el-table-column prop="approvalNo"  width="120" header-align="center" align="center" label="批准文号">
      </el-table-column>
      <el-table-column prop="produceFactory"  width="160" header-align="center" align="center" label="厂家">
      </el-table-column>
      <el-table-column prop="dosageForm"  width="120" header-align="center" align="center" label="剂型">
      </el-table-column>
      <el-table-column prop="expiredDate" width="120" header-align="center" align="center" label="有效期">
        <template slot-scope="scope">
           <el-date-picker
                 v-model="scope.row.expiredDate"
                 type="date"
                 v-if="showInput == `expiredDate${scope.row.stockId}`"
                 @blur='blurInput(scope.row, "expiredDate", scope.row.expiredDate)'
                 value-format="yyyy-MM-dd"
                 placeholder="选择日期"
                 v-focus>
               </el-date-picker>
           <span v-else>{{scope.row.expiredDate}}</span>
         </template>
      </el-table-column>
      <el-table-column prop="isMedicare" header-align="center" align="center" label="医保">
      </el-table-column>
      <el-table-column prop="isChinaDrug" header-align="center" align="center" label="中药">
      </el-table-column>
      <el-table-column prop="isGmp" header-align="center" align="center" label="gmp药">
      </el-table-column>
      <el-table-column prop="effect" header-align="center" align="center" label="效果">
      </el-table-column>
      <el-table-column prop="brandName" header-align="center" align="center" label="品牌名称">
      </el-table-column>
      <el-table-column prop="isCommission" header-align="center" align="center" label="是否提成">
      </el-table-column>
      <el-table-column prop="commissionRatio" header-align="center" align="center" label="提成比例">
      </el-table-column>
      <el-table-column prop="operatorName" header-align="center" align="center" label="经办人">
      </el-table-column>
      <el-table-column prop="createTime" width="140" header-align="center" align="center" label="创建时间">
      </el-table-column>
      <el-table-column prop="updateTime" width="140" header-align="center" align="center" label="修改时间">
      </el-table-column>
      <!-- <el-table-column prop="createUsername" header-align="center" align="center" label="创建人">
      </el-table-column>
      <el-table-column prop="updateUsername" header-align="center" align="center" label="修改人">
      </el-table-column> -->
      <el-table-column prop="remark" header-align="center" align="center" label="备注">
      </el-table-column>
     <!-- <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="addOrUpdateHandle(scope.row.stockId)">保存</el-button>
          <el-button type="text" size="mini" @click="addOrUpdateHandle(scope.row.stockId)">修改</el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
  </div>
</template>

<script>
  import AddOrUpdate from './goodsstock-add-or-update'
  import {downLoadFile} from '@/utils/myUtil.js'
  export default {
    data() {
      return {
        dataForm: {
          key: ''
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        showInput: "",
        oldData: {},
        currentData: {},

        selectFields: [],
        priceFields: [],
        queryFields: [],
        priceFormulas: [],
        units: [],
        supplies: [],
        goods: {},
      }
    },
    components: {
      AddOrUpdate
    },
    activated() {
      this.getDataList()
      this.initData()
      this.getUnits()
    },
    methods: {
      initData() {
        let selectFields = [{
            value: 'is_rx_drug',
            label: '是否处方'
          }, {
            value: 'is_medicare',
            label: '是否医保'
          }, {
            value: 'is_china_drug',
            label: '是否中药'
          }, {
            value: 'is_commission',
            label: '是否提成'
          }, {
            value: 'is_gmp',
            label: '是否GMP药'
          }
        ];

        let priceFields = [{
          value: 'stock_total_num',
          label: '总库存'
        },
        {
          value: 'purchase_num',
          label: '采购数量'
        },{
          value: 'sale_price',
          label: '售价'
        }, {
          value: 'guide_price',
          label: '指导零售价'
        }, {
          value: 'member_price',
          label: '会员价'
        }];
        let priceFormulas = [{
          value: 'GE',
          label: '大于等于'
        }, {
          value: 'EQ',
          label: '等于'
        }, {
          value: 'GT',
          label: '大于'
        }, {
          value: 'LE',
          label: '小于等于'
        }, {
          value: 'LT',
          label: '小于'
        }, {
          value: 'NE',
          label: '不等于'
        }, ]


        let queryFields = [{
          value: 'goods_code',
          label: '编码'
        }, {
          value: 'bar_code',
          label: '条形码'
        }, {
          value: 'goods_name',
          label: '产品名称'
        }, {
          value: 'generic_name',
          label: '通用名'
        }, {
          value: 'producing_area',
          label: '产地'
        }, {
          value: 'produce_factory',
          label: '厂家'
        }, {
          value: 'dosage_form',
          label: '剂型'
        }, {
          value: 'standard',
          label: '规格'
        }, {
          value: 'effect',
          label: '效果'
        }, {
          value: 'approval_no',
          label: '批准文号'
        }, {
          value: 'brand_name',
          label: '品牌名称'
        }]

        this.selectFields = selectFields;
        this.priceFields = priceFields;
        this.priceFormulas = priceFormulas;
        this.queryFields = queryFields;
      },
      async getUnits() {
        const res = await this.$http({
          url: '/base/basedict/getDict',
          method: 'get',
          params: this.$http.adornParams({
            'code': 'UNIT'
          })
        })
        let data = res.data
        if (data && data.code === 0) {
          this.units = data.data
        }
      },
      // 获取数据列表
      getDataList() {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/goods/goodsstock/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'dataForm': this.dataForm
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {

            this.dataList = data.page.list
            this.totalPage = data.page.totalCount

            this.dataList.forEach(item => {
              item.status = item.status == 1 ? true : false
              item["edit"] = false;
            })


          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle(val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle(id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 删除
      deleteHandle(id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/goods/goodsstock/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({
            data
          }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      saveHandle(row){
        this.$confirm(`您确定要修改吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
            row.status = row.status ? 1 : 0
            const res = await this.$http({
                 url:`/goods/goodsstock/update`,
                 method: 'post',
                 data: this.$http.adornData(row)
            });
            let data = res.data
            if (data && data.code !== 0) {
              row.status = !row.status;
              return this.$message.error('修改失败!');
            }
            this.$message.success('更新成功！');
            this.getDataList();
        })
      },
      // 当input失去光标后进行的操作
      async blurInput(row, name, value) {
        // 判断数据是否有所改变，如果数据有改变则调用修改接口
        if (this.oldData[name] != value) {
          row[name] = value
          if(value === true){
            row[name] = 1

          }else if(value === false){
            row[name] = 0
          }

          //保存数据
          this.saveHandle(row)
        }
        this.showInput = ""
        this.currentData = row

      },
      tableDbEdit(row, column, event) {
        this.showInput = column.property + row.stockId
        this.oldData[column.property] = row[column.property]
      },
      async exportData(){
        const res = await this.$http({
             url:`/goods/goodsstock/exportData`,
             method: 'get',
             responseType: 'blob',
             params: this.$http.adornParams()
        });
        downLoadFile(res)
      },
      resetForm(){
        this.$nextTick(() =>{
          this.dataForm = this.$options.data().dataForm
          this.getDataList()
        })
      },


    },
    directives: {
      // 通过自定义指令实现的表单自动获得光标的操作
      focus: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "input") {
            el.focus()
          } else {
            if (el.getElementsByTagName("input")) {
              el.getElementsByTagName("input")[0].focus()
            }
          }
          el.focus()
        }
      },
      focusTextarea: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "textarea") {
            el.focus()
          } else {
            if (el.getElementsByTagName("textarea")) {
              el.getElementsByTagName("textarea")[0].focus()
            }
          }
          el.focus()
        }
      }
    },
  }
</script>
<style lang="less" scoped>
  .el-col:nth-child(2) {
    padding-left: 20px;
  }
  .el-select {
    max-width: 100px;
  }
  .el-table__cell{
    padding: 0!important;
    margin: 0!important;
  }
  .el-input{
    margin: 0px;
  }
</style>
